

This project is part of the
@thi.ng/umbrella monorepo.
About
Configurable k-means & k-medians (with k-means++ initialization) for n-D vectors.
Status
BETA - possibly breaking changes forthcoming
Search or submit any issues for this package
Installation
yarn add @thi.ng/k-means
ES module import:
<script type="module" src="https://cdn.skypack.dev/@thi.ng/k-means"></script>
Skypack documentation
For Node.js REPL:
const kMeans = await import("@thi.ng/k-means");
Package sizes (brotli'd, pre-treeshake): ESM: 906 bytes
Dependencies
Usage examples
Several demos in this repo's
/examples
directory are using this package.
A selection:
Screenshot | Description | Live demo | Source |
---|
 | Color palette generation via dominant color extraction from uploaded images | Demo | Source |
 | Image dithering and remapping using indexed palettes | Demo | Source |
API
Generated API docs
Example usage:
import { kmeans, meansLatLon } from "@thi.ng/k-means";
import { HAVERSINE_LATLON } from "@thi.ng/distance";
const items = [
{ id: "berlin", latlon: [52.5167, 13.3833] },
{ id: "boston", latlon: [42.3188, -71.0846] },
{ id: "detroit", latlon: [42.3834, -83.1024] },
{ id: "kyoto", latlon: [35.0111, 135.7669] },
{ id: "london", latlon: [51.5072, -0.1275] },
{ id: "new york", latlon: [40.6943, -73.9249] },
{ id: "osaka", latlon: [34.6936, 135.5019] },
{ id: "paris", latlon: [48.8566, 2.3522] },
{ id: "philadelphia", latlon: [40.0077, -75.1339] },
{ id: "tokyo", latlon: [35.6897, 139.6922] },
{ id: "vienna", latlon: [48.2083, 16.3731] },
];
const clusters = kmeans(
3,
items.map((x) => x.latlon),
{
strategy: meansLatLon,
dist: HAVERSINE_LATLON
}
);
for (let c of clusters) {
console.log(c.items.map((i) => items[i].id));
}
Authors
If this project contributes to an academic publication, please cite it as:
@misc{thing-k-means,
title = "@thi.ng/k-means",
author = "Karsten Schmidt",
note = "https://thi.ng/k-means",
year = 2021
}
License
© 2021 - 2023 Karsten Schmidt // Apache License 2.0